package com.fileServer.fileHandler;

import com.fileServer.constants.CourseFileConstants;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
import java.util.*;


/**
 * 由于SimpleUrlHandlerMapping返回的ResourceHttpRequestHandler存在对中文字符重复解码的问题,所以这里自定义
 * @author 大忽悠
 * @create 2023/2/28 10:15
 */
public class CustomFileHandlerMapping extends AbstractUrlHandlerMapping implements ApplicationContextAware{
    private final Map<String, Object> urlMap = new LinkedHashMap<>();
    private final CustomFileResourceHttpRequestHandler fileResourceHttpRequestHandler;

    public CustomFileHandlerMapping(CustomFileResourceHttpRequestHandler resourceHttpRequestHandler) {
        this.fileResourceHttpRequestHandler=resourceHttpRequestHandler;
        //添加文件映射路径
        urlMap.put(CourseFileConstants.STATIC_REQUEST_PREFIX_PATTERN,fileResourceHttpRequestHandler);
    }

    @Override
    public void initApplicationContext() throws BeansException {
        super.initApplicationContext();
        registerHandlers(this.urlMap);
    }

    protected void registerHandlers(Map<String, Object> urlMap) throws BeansException {
        if (urlMap.isEmpty()) {
            logger.trace("No patterns in " + formatMappingName());
        }
        else {
            urlMap.forEach((url, handler) -> {
                // Prepend with slash if not already present.
                if (!url.startsWith("/")) {
                    url = "/" + url;
                }
                // Remove whitespace from handler bean name.
                if (handler instanceof String) {
                    handler = ((String) handler).trim();
                }
                registerHandler(url, handler);
            });
            if (logger.isDebugEnabled()) {
                List<String> patterns = new ArrayList<>();
                if (getRootHandler() != null) {
                    patterns.add("/");
                }
                if (getDefaultHandler() != null) {
                    patterns.add("/**");
                }
                patterns.addAll(getHandlerMap().keySet());
                logger.debug("Patterns " + patterns + " in " + formatMappingName());
            }
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
